using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LS.UnityExtensions;

namespace LS.Digitize
{
    public static class SerializerManager
    {
        private static object s_LockObj = new object();

        internal static readonly Dictionary<Type, ISerializer> SerializersTypeMap = new Dictionary<Type, ISerializer>();
        
        public static int Count => SerializersTypeMap.Count;
        
        private static ISerializer s_CacheSerializer = null;
        
        public static ISerializer GetSerializer(Type type)
        {
            if (type != typeof(object) && s_CacheSerializer != null && type == s_CacheSerializer.DataType)
                return s_CacheSerializer;
            
            if (SerializersTypeMap.TryGetValue(type, out ISerializer ser))
            {
                s_CacheSerializer = ser;
                return ser;
            }

            return null;
        }

        public static bool HasSerializer(Type type)
        {
            return SerializersTypeMap.ContainsKey(type);
        }

        public static void Add(Type type, ISerializer ser)
        {
            if (SerializersTypeMap.TryGetValue(type, out ISerializer ser2))
            {
                if (ser2 == ser || ser2.Priority < ser.Priority) return;
            }

            lock (s_LockObj)
            {
                SerializersTypeMap[type] = ser;
            }
        }

        public static void Remove(Type type)
        {
            lock (s_LockObj)
            {
                SerializersTypeMap.Remove(type);
            }
        }
    }
}